<?php

namespace app\home\controller;

use app\common\controller\Home;
use think\Request;
use think\Cookie;
use app\common\controller\Home AS HomeController;
use think\Console;

class Comment extends HomeController
{
    public function __construct()
    {
        parent::__construct();

        $this->CommentModel = model('Post.Comment');
        $this->PostModel = model('Post.Post');
        $this->UserModel = model('User.User');
        $this->RecordModel = model('User.Record');

    }
    //添加评论
    public function add()
    {
        if($this->request->isPost())
        {
            // 接收帖子id
            $postid = $this->request->param('postid',0);

            $post = $this->PostModel->find($postid);

            if(!$post)
            {
                $this->error('帖子已删除，请重新选择');
                exit;
            }

            // 评论上一级id
            $pid = $this->request->param('pid',0);
            // 评论内容
            $content = $this->request->param('content','');

            // 去掉where条件 查询评论表是否该条评论
            $comment = $this->CommentModel->find($pid);

            if($comment)
            {
                // 评论等级字段 需要+1
                $level = $comment['level'] + 1;
                
            }else{
                // 设置为0
                $level = 0;
                
            }

            // 封装数据
            $data = [
                'pid' => $pid,
                'content' => $content,
                'level' => $level,
                'userid' => $this->LoginUser['id'],
                'postid' => $postid,
                'accept' => 0
            ];

            $result = $this->CommentModel->validate('common/Post/Comment')->save($data);

            if($result === FALSE)
            {
                $this->error($this->CommentModel->getError());
                exit;
            }else{
                $this->success('评论成功',url("home/index/info",['postid' => $postid]));
            }


        }
    }
    // 点赞
    public function like()
    {
        if ($this->request->isAjax())
        {
            $comid = $this->request->param('comid', 0);

            $Comment = $this->CommentModel->find($comid);

            $data = [
                'code' => 0,
                'msg' => '未知信息'
            ];

            if(!$Comment)
            {
                $data['msg'] = '该评论无法点赞';
                echo json_encode($data);
                exit;
            }

            $likeArr = explode(',',$Comment['like']);
            $likeArr = array_filter($likeArr);

            $Userid = $this->LoginUser['id'];

            if(!in_array($Userid,$likeArr))
            {
                $likeArr[] = $Userid;
                // halt($likeArr);

                $likeData = [
                    'id' => $comid,
                    'like' => implode(',',$likeArr),
                ];

                $result = $this->CommentModel->isUpdate(true)->save($likeData);

                if($result === FALSE)
                {
                    $data['msg'] = '该评论无法点赞，请重新点赞';
                    echo json_encode($data);
                    exit;
                }else{
                    $data['code'] = 1;
                    $data['msg'] = '已点赞';
                    echo json_encode($data);
                    exit;
                }
            }else{
                foreach($likeArr as $key => $item)
                {
                    if($Userid == $item)
                    {
                        unset($likeArr[$key]);
                        break;
                    }
                }
                // halt($likeArr);
                $likeData = [
                    'id' => $comid,
                    'like' => implode(',',$likeArr),
                ];

                $result = $this->CommentModel->isUpdate(true)->save($likeData);

                if($result === FALSE)
                {
                    $data['msg'] = '该评论无法点赞，请重新点赞';
                    echo json_encode($data);
                    exit;
                }else{
                    $data['code'] = 2;
                    $data['msg'] = '已取消点赞';
                    echo json_encode($data);
                    exit;
                }
            }
        }
    }
    //采纳
    public function accept()
    {
        if($this->request->isAjax())
        {
            // 获取评论id
            $comid = $this->request->param('comid',0);

            // 封装返回接口数据
            $result = [
                'code' => 0,
                'msg' => '未知信息'
            ];

            $comment = $this->CommentModel->find($comid);

            if(!$comment)
            {
                $result['msg'] = '评论已删除，无法采纳';
                return Json($result);
            }

            $Comment = $this->CommentModel->with('user','post')->find($comid);

            if($Comment['accept'] == 1 || $Comment['post']['accept'])
            {
                $result['msg'] = '评论已被采纳';
                return Json($result);
            }

            // 评论表 accept 0 = 1
            // 帖子表 accept null = userid => 该条评论的用户
            // 用户表 point 更新 => 被采纳用户的积分
            // 用户消费记录表 新增记录

            // 开启事务
            $this->PostModel->startTrans();
            $this->UserModel->startTrans();
            $this->RecordModel->startTrans();
            $this->CommentModel->startTrans();

            // 更新评论采纳状态
            $AcceptData = [
                'id' => $comid,
                'accept' => 1
            ];


            // 更新
            $CommentStatus = $this->CommentModel->isUpdate(true)->save($AcceptData);

            if($CommentStatus === FALSE)
            {
                $result['msg'] = $this->CommentModel->getError();
                return Json($result);
            }

            // 更新帖子的采纳id
            $PostData = [
                'id' => $Comment['postid'],
                'accept' => $Comment['userid']
            ];

            // 更新
            $PostResult = $this->PostModel->isUpdate(true)->save($PostData);

            if($PostResult === FALSE)
            {
                $this->CommentModel->rollback();
                $result['msg'] = $this->PostModel->getError();
                return Json($result);
                
            }

            // 用户积分
            $UserPoint = $Comment['user']['point'];
            // 帖子悬赏积分
            $PostPoint = $Comment['post']['point'];

            $Point = bcadd($UserPoint,$PostPoint);

            // 更新用户的积分
            $UserData = [
                'id' => $Comment['userid'],
                'point' => $Point
            ];

            // 更新
            $UserResult = $this->UserModel->isUpdate(true)->save($UserData);

            if($UserResult === FALSE)
            {
                $this->CommentModel->rollback();
                $this->PostModel->rollback();
                
                $result['msg'] = $this->UserModel->getError();
                return Json($result);
            }


            // RecordModel
            $RecordData = [
                'point' => $PostPoint,
                'content' => "【".$Comment['content']."】获取积分:<b>".$PostPoint."</b>积分 - 获取时间：".date("Y-m-d H:i"),
                'state' => 2,
                'userid' => $Comment['userid']
            ];

            // 更新
            $RecordResult = $this->RecordModel->save($RecordData);

            if($RecordResult === FALSE)
            {
                $this->CommentModel->rollback();
                $this->PostModel->rollback();
                $this->UserModel->rollback();
                $result['msg'] = $this->RecordModel->getError();
                return Json($result);
            }


            // 最终判断
            if($RecordResult === FALSE || $UserResult === FALSE || $PostResult === FALSE || $CommentStatus === FALSE)
            {
                $this->CommentModel->rollback();
                $this->PostModel->rollback();
                $this->UserModel->rollback();
                $this->RecordModel->rollback();
                $result['msg'] = '采纳失败，请重新选择';
                return Json($result);
            }else{
                $this->CommentModel->commit();
                $this->PostModel->commit();
                $this->UserModel->commit();
                $this->RecordModel->commit();
                $result['code'] = 1;
                $result['msg'] = '采纳成功';
                return Json($result);
            }
        }
    }

   //删除评论
   public function del()
   {
       $success = [
           'result' => false,
           'msg' => ''
       ];
       if($this->request->isPost()){
           $com = $this->request->param();
           $pid = $com['pid'];
           //根据id去查询这个评论是否存在
           $comment = $this->CommentModel->find($pid);

       
           $post = $this->PostModel->find($comment['postid']);
    
           if(!$comment)
           {
               $this->error('删除的评论不存在');
               exit;
           }
         
           //判断登录用户id  和 发帖人的userid 是否相同
           if($post['userid'] != $this->LoginUser['id'])
           {
               $this->error('无权删除此评论');
               exit;
           }

           
           $User = empty(Cookie::get('LoginUser')) ? [] : Cookie::get('LoginUser');

           $commentlist = $this->CommentModel->with(['user'])
                           ->where(['postid' => $post['id']])
                           ->order('id', 'asc')
                           ->order('level', 'asc')
                           ->select();

           $commentlist=CommentTree($commentlist, $pid, $User);
           // var_dump($commentlist);
           $comentid = [];
       
        //    $comentid = CommentIdTree($commentlist,$comentid);
           array_push($comentid,$pid);
           // var_dump($comentid);
    

           // $commentlist = $this->CommentModel->where(['id'=>$pid])->find();
           //直接删除 软删除
           $result = $this->CommentModel->destroy($comentid);

  

           if($result === FALSE)
           {
               //删除失败
               $success['result'] = false;
               $success['msg'] = $this->PostModel->getError();
           }else
           {
               //删除成功
               $success['result'] = true;
               $success['msg'] = '删除成功';
           }

           //将结果返回给ajax
           return json($success);
           
       }
   }
}
